<?php
namespace Home\Controller;

use Think\Controller;

class IndexController extends SignInController
{
    /**
     * 首页
     */
    public function index()
    {
        if(IS_POST){

        }else{
            // 轮播图
            $account=parent::get("account");
            if(empty($account)){
                $this->redirect("Home/Login/login");
            }
            $show = getIndexShow();
            $this->assign('showImg', $show);
            $this->display();
        }
    }


    /*轮播图*/
    public function show()
    {
        // 轮播图
        $show = getIndexShow();
        return $this->ajaxSuccess($show);
    }

    /*公告*/
    public function notice()
    {
        $notice = getMemberNotice();
        return $this->ajaxSuccess($notice);
    }

    /*常见问题*/
    public function question()
    {
        $question = getMemberQuestion();
        return $this->ajaxSuccess($question);
    }

    //获取商品分类
    public function getCates()
    {
        $cates = getAllCates();
        return $this->ajaxSuccess($cates);
    }

    /*公告详情*/
    public function noticeDetail()
    {
        $id = (int)I("id");
        if (empty($id)) $this->ajaxError("参数错误：未知的公告id！");
        $Notice = M('article')->where(array('id' => $id))->find();
        return $this->ajaxSuccess($Notice);
    }

    /*常见问题详情*/
    public function questionDetail()
    {
        $id = I("id");
        $Notice = M('article')->where(array('id' => $id))->find();
        return $this->ajaxSuccess($Notice);
    }

    /*公司简介*/
    public function company()
    {
        // 公司简介
        $intro = getIndexCompany();
        return $this->ajaxSuccess($intro);
    }

    /*产品展示*/
    public function product()
    {
        //产品
        $list = getIndexProduct();
        return $this->ajaxSuccess($list);
    }

    /*附近代理商*/
    public function nearbyagent()
    {
        $memberlng = I('post.memberlng'); //经度
        $memberlat = I('post.memberlat'); //纬度
        $memberlng = NumEToNum($memberlng);
        $memberlat = NumEToNum($memberlat);
        if (empty($memberlat) && empty($memberlng)) {
            $lnglat = parent::getLngLat();
            $memberlng = $lnglat[0];
            $memberlat = $lnglat[1];
        }
        $where = "status = 2 and isDisable = 2 and a.id != 1";
        //获取该城市的一级代理
        $dAgens = $this->getCityAgen($memberlng,$memberlat);
        if(!empty($dAgens)){
            //排序
            foreach ($dAgens as $vv) {
                $djl[] = $vv['juli'];
                $dlev[] = $vv['level'];
            }
            array_multisort($djl, $dlev, SORT_ASC, $dAgens);
            $dIds = '(';
            for($i = 0;$i < count($dAgens);$i ++){
                $dIds = $dIds.$dAgens[$i]['id'];
                if($i < count($dAgens)-1){
                    $dIds = $dIds.",";
                }
            }
            $dIds = $dIds.")";
            $where = $where." and a.id not in $dIds";
        }

        $agenlist = M('agen')
            ->alias("a")
            ->join(" left join region r ON a.regionId=r.id")
            ->join(" left join agenlevel l ON l.id = a.level")
            ->field('a.*,r.name_path,l.name levelname')
            ->where($where)
            ->select();
        for($i = 0;$i < count($agenlist);$i ++){
            $agenlat = $agenlist[$i]['lat'];
            $agenlng = $agenlist[$i]['lng'];
            $agenlist[$i]['juli'] = $this->getDistance($memberlat, $memberlng, $agenlat, $agenlng);
        }
        //排序
        foreach ($agenlist as $vv) {
            $jl[] = $vv['juli'];
            $lev[] = $vv['level'];
        }
        array_multisort($jl, $lev, SORT_ASC, $agenlist);
        //获取所有的组合起来
        for ($i = 0; $i < 5 + count($dAgens); $i++) {
            if ($i < count($dAgens)) {
                $list[] = $dAgens[$i];
            } else {
                if ($agenlist[$i] != null) {
                    $list[] = $agenlist[$i];
                }
            }
        }
        return $this->ajaxSuccess($list);
    }

    //获取该城市的一级代理
    public function getCityAgen($memberlng,$memberlat){
        $region = parent::getRegionByLngLat($memberlng,$memberlat);
        if(empty($region)){
            return array();
        }
        $districtId = $region['id'];
        $cityId = $region['parent_id'];
        //获取当前县区的一级代理
        $dAgens = M('agen')
            ->alias("a")
            ->join(" left join region r ON a.regionId=r.id")
            ->join(" left join agenlevel l ON l.id = a.level")
            ->field('a.*,r.name_path,l.name levelname')
            ->where("a.regionId = $districtId and a.`level` = 1 and a.`status` = 2 and a.isDisable = 2 and a.id != 1")
            ->select();
        if(empty($dAgens)){
            //没有则获取上级下所有县区的一级代理
            $cityDsts = M('region')
                ->field('id')
                ->where(array('parent_id'=>$cityId))
                ->select();
            $dIds = '(';
            for($i = 0;$i < count($cityDsts);$i ++){
                $dIds = $dIds.$cityDsts[$i]['id'];
                if($i < count($cityDsts)-1){
                    $dIds = $dIds.",";
                }
            }
            $dIds = $dIds.")";
            $dAgens = M('agen')
                ->alias("a")
                ->join(" left join region r ON a.regionId=r.id")
                ->join(" left join agenlevel l ON l.id = a.level")
                ->field('a.*,r.name_path,l.name levelname')
                ->where("a.regionId in $dIds and a.`level` = 1 and a.`status` = 2 and a.isDisable = 2 and a.id != 1")
                ->select();
        }
        //添加距离信息
        for($i = 0;$i < count($dAgens);$i ++){
            $agenlat = $dAgens[$i]['lat'];
            $agenlng = $dAgens[$i]['lng'];
            $dAgens[$i]['juli'] = parent::getDistance($memberlat, $memberlng, $agenlat, $agenlng);
        }
        return $dAgens;
    }

    //url获取代理或会员
    public function geturlagen()
    {
        $url = I('post.id');
        $memacc = I('post.memacc');
        if (!empty($url)) {
            $agen = M('agen')->where("agenNo = '$url'")->find();
            if (empty($agen)) {
                $this->ajaxError("代理URL不存在");
            } else {
                $this->ajaxSuccess(array('agen' => $agen, 'flag' => 1));
            }
        } else if (!empty($memacc)) {
            parent::set('parentmember', $memacc);
            $agen = M('member')
                ->alias("m")
                ->join("LEFT JOIN agen a ON m.belongAgenId=a.id")
                ->where("m.account = $memacc")->field("a.account")->find();
            $this->ajaxSuccess(array('memacc' => $memacc, 'agen' => $agen, 'flag' => 2));
        }
    }

    //会员注册获取代理
    public function regnearbyagent()
    {
        $memacc = parent::get('parentmember');
        $memberlat = I('post.memberlat'); //纬度
        $memberlng = I('post.memberlng'); //经度
        $agen = M('agen')
            ->alias("a")
            ->join(" left join region r ON a.regionId=r.id")
            ->field('a.id,a.name,a.account,a.lat,a.lng,r.name_path')
            ->where('status = 2')
            ->select();
        $agenlist = array();
        foreach ($agen as $v) {
            $agenlat = $v['lat'];
            $agenlng = $v['lng'];
            $agenlist[] = array('id' => $v['id'], 'name' => $v['name'], 'account' => $v['account'], 'name_path' => $v['name_path'], 'juli' => $this->getDistance($memberlat, $memberlng, $agenlat, $agenlng));
        }
        foreach ($agenlist as $vv) {
            $jl[] = $vv['juli'];
        }
        array_multisort($jl, SORT_ASC, $agenlist);
        for ($i = 0; $i < 5; $i++) {
            if ($agenlist[$i] != null) {
                $list[] = $agenlist[$i];
            }
        }
        return $this->ajaxSuccess(array('agen' => $list[0], 'memacc' => $memacc));
    }

    /*代理查询*/
    public function selagen()
    {
        if (IS_POST) {
            $check = I('post.check');
            $agenlist = M("agen")
                ->alias("a")
                ->join(" left join region r ON a.regionId=r.id")
                ->join(" left join agenlevel l ON l.`level`=a.`level`")
                ->where("(a.account='$check' OR a.webchat='$check' OR a.phone='$check') AND a.status='2'")
                ->field('a.*,r.name_path,l.name levelname')
                ->order("id desc")
                ->select();
            $memberlng = I('post.memberlng'); //经度
            $memberlat = I('post.memberlat'); //纬度
            $memberlng = NumEToNum($memberlng);
            $memberlat = NumEToNum($memberlat);
            if (empty($memberlat) && empty($memberlng)) {
                $lnglat = parent::getLngLat();
                $memberlng = $lnglat[0];
                $memberlat = $lnglat[1];
            }
            for ($i = 0; $i < sizeof($agenlist); $i++) {
                $agenlist[$i]['juli'] = $this->getDistance($memberlat, $memberlng, $agenlist[$i]['lat'], $agenlist[$i]['lng']);
            }
            if ($agenlist) {
                return $this->ajaxSuccess($agenlist);
            } else {
                return $this->ajaxError("未找到该代理！");
            }
        }
//      else{
//            $agenlist = M("agen")
//                ->order("id desc")
//                ->field("id,name,webchat,phone")
//                ->select();
//            return $this->ajaxSuccess($agenlist);
//
//        }
    }

    /*代理标识*/
    public function getAgenUrl()
    {
        $agen = parent::get('urlagen');
        if (!empty($agen)) {
            $this->ajaxSuccess($agen);
        } else {
            $this->ajaxSuccess(null);
        }
    }

    /*标题栏显示代理标识*/
    public function agenUrl()
    {
        //链接代理url
        $url = I('post.id');
        //代理等级表
        //$agenlevel = M("agenlevel") ->select();
        if (empty($url) || $url == '' || $url == null) {
            //非代理URL
            parent::remove('urlagen');
            $this->ajaxSuccess("非代理URL");
        } else {
            //代理url存在 获取并保存当前代理
            $agenBean = M("agen")
                ->where(array("agenNo" => $url, "status" => 2))
                ->find();
            if (!empty($agenBean)) {
                parent::set('urlagen', $agenBean);
                $this->ajaxSuccess($agenBean);
            } else {
                $this->ajaxError("此代理URL不存在");
            }
        }
    }

    /*用户退出*/
    public function quit()
    {
        unset($_SESSION['member_name']);
        unset($_SESSION['userinfo']);
        unset($_SESSION['cart']);
        $this->redirect("index");
    }

    //验证码是否正确
    public function checkCode()
    {
        $code = I("code");
        $verify = new \Think\Verify();
        $verify->reset = false;
        echo !$verify->check($code);
    }

    /*搜索商品*/
    public function searchgoods()
    {
        if (isset($_POST['sub'])) {
            $goodsname = I("searchgoods");
            D("Goods")->searchGoods($goodsname);
        }
    }

    /*检查会员是否存在*/
    function checkusername()
    {
        $name = I("username");
        $res = M("member")->where("username='" . $name . "'")->find();
        if ($res) {
            $this->ajaxReturn(array("error" => "此会员已存在"));
        } else {
            $this->ajaxReturn(array("ok" => ""));
        }
    }

    /*检查会员是否存在*/
    function checkparentname()
    {
        $name = I("parentname");
        $res = M("member")->where("username='" . $name . "'")->find();
        if ($res) {
            $this->ajaxReturn(array("ok" => "存在推荐人"));
        } else {
            $this->ajaxReturn(array("error" => "不存在推荐人账号"));
        }
    }

    //代理详情
    public function agenDetail()
    {
        $id = I('id');
        $agen = M("agen")
            ->alias('a')
            ->field('a.*,l.name levelname')
            ->join('left join agenlevel l on l.`level` = a.`level`')
            ->where(array("a.id" => $id, 'a.`status`' => 2))
            ->find();
        $aurl = explode("=", $agen['agenurl'])[1];
        $this->ajaxSuccess(array('agen' => $agen, 'aurl' => $aurl));
    }

    //代理注册获取urlid
    public function registeragen()
    {
        $agen_id = explode("=", parent::get("urlagen")['agenurl'])[1];
        $this->ajaxSuccess($agen_id);
    }

    //生成token
    public function makeToken()
    {
        if (IS_POST) {
            $curtoken = parent::get('token');
            if ($curtoken == null || empty($curtoken)) {
                $token = make_order_sn();

                $session = S($token);
                // 如果没有数据
                if (empty($session)) {
                    $session = array();
                }
                $session['token'] = $token;
                S($token, $session);

                $this->ajaxSuccess(array('token' => $token));
            } else {
                $this->ajaxSuccess(array('token' => $curtoken));
            }
        }
    }

    public function usermessage()
    {
        $id = parent::get("account")['id'];
        $member = M("member")
            ->field("id,nickname,account,parentId,parentAccount,balance,integral,invitecode,profilePhoto,sign_time")
            ->where("id='".$id."'")
            ->find();
        //ajax获取金额
        $system=getConfig("rakeback");
        $user=M("member")->where(array("id"=>$id))->find();
        if(empty($user['signtime']) || date("Y-m-d", strtotime($user['signtime'])) != date("Y-m-d", time())){
            $sign_balance=$user['integral']*$system['signRate'];
            $res=M("member")->where(array("id"=>$id))->save(array("sign_balance"=>$sign_balance));//首页之前添加签到余额
            $member['sign_balance']=$sign_balance+$user['other_balance'];//静态释放的余额+余额变更和积分兑换的
        }
        if(date('Y-m-d',strtotime($member['sign_time']))==date('Y-m-d')){
            $member['sign']=true;//已签到
        }else{
            $member['sign']=false;
        }
        if ($member) {
            $this->ajaxSuccess($member);
        } else {
            $this->ajaxError('请登录！');
        }
    }

    /**
     * 签到积分释放
     */
    public function sign_balance()
    {
        if (!empty(parent::get("LAST_ADD_SIGN")) && time() - parent::get("LAST_ADD_SIGN") <= 10) $this->ajaxError();
        parent::set("LAST_ADD_SIGN", time());

        $user = parent::getAccount();
        M()->startTrans();
        $static_balance=bcadd($user['balance'], $user['sign_balance'], 2);
        $balance=$static_balance+$user['other_balance'];
        $integral= $user['sign_balance']+$user['other_balance'];
        if($user['integral']>0 && $user['integral']<$integral){//有积分但是不够扣的，改为0；
            $reduceItg=$user['integral'];//减少积分
            $remainitg=0;//剩余积分
        }else if($user['integral']>0 && $user['integral']>$integral){
            $reduceItg=$integral;//减少积分
            $remainitg=$user['integral']-$integral;//剩余积分
        }else{//积分为0的时候
            $reduceItg=0;
            $remainitg=0;
        }

        $data=array(
            "balance"=>$balance,
            "sign_balance"=>0,
            "other_balance"=>0,
            "sign_time"=>now_datetime(),
            'integral' => $remainitg,
        );
        $res = M("member")->where(array("id"=>$user['id']))->save($data);
        if($balance>=0.01){
            $add_log = balancelog($res, $user['id'],$balance, $type=5, $before=$user['balance'], $after=$user['balance']+$balance);
        }else{
            $add_log=1;
        }
        if($reduceItg>=0.01){
            $inte_log=integrallog($res, $user['id'],-$reduceItg,4,$user['integral'],$remainitg);//返佣积分log
        }else{
            $inte_log=1;
        }
        //$inte_log = integrallog($res, $user['id'],-$user['sign_balance'], $type=4, $before=$user['integral'], $after=$user['integral'] - $user['sign_balance']);
        if (empty($res) || empty($add_log) || empty($inte_log)) {
            M()->rollback();
            $this->ajaxError('签到失败！');
        } else {
            M()->commit();
            $this->ajaxSuccess("签到成功！");
        }

    }

    /**
     * 签到积分释放
     */
    public function signOut()
    {
        $user = parent::get("account");
        $data=array(
            "sign_balance"=>0,
            "sign_time"=>now_datetime()
        );
        $res = M("member")->where(array("id"=>$user['id']))->save($data);
        if (empty($res)) {
            $this->ajaxError('签到失败！');
        } else {
            $this->ajaxSuccess("签到成功！");
        }
    }
}